"""
WebSocket API端点
提供实时数据推送和订阅功能
"""

from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect, HTTPException
from typing import Optional
from loguru import logger

from core.auth import get_current_user
from services.websocket_service import real_time_service

# 创建路由器
websocket_router = APIRouter(prefix="/api/ws", tags=["WebSocket"])


@websocket_router.websocket("/statistics/{user_id}")
async def websocket_statistics(
    websocket: WebSocket,
    user_id: int
):
    """
    统计数据WebSocket端点
    实时推送统计数据的更新
    """
    try:
        logger.info(f"用户 {user_id} 连接统计数据WebSocket")
        await real_time_service.handle_websocket(websocket, str(user_id))
    except Exception as e:
        logger.error(f"WebSocket连接错误: {e}")
        await websocket.close(code=1011, reason="服务器内部错误")


@websocket_router.websocket("/dashboard/{user_id}")
async def websocket_dashboard(
    websocket: WebSocket,
    user_id: int
):
    """
    仪表盘WebSocket端点
    实时推送仪表盘数据的更新
    """
    try:
        logger.info(f"用户 {user_id} 连接仪表盘WebSocket")
        await real_time_service.handle_websocket(websocket, str(user_id))
    except Exception as e:
        logger.error(f"WebSocket连接错误: {e}")
        await websocket.close(code=1011, reason="服务器内部错误")


@websocket_router.get("/stats")
async def get_websocket_stats():
    """
    获取WebSocket连接统计信息
    """
    try:
        from services.websocket_service import manager
        stats = manager.get_connection_stats()
        return {
            "code": 200,
            "message": "success",
            "data": stats
        }
    except Exception as e:
        logger.error(f"获取WebSocket统计信息失败: {e}")
        raise HTTPException(status_code=500, detail="获取统计信息失败")


@websocket_router.post("/broadcast")
async def broadcast_message(
    message: str,
    topic: str = "all",
    current_user: dict = Depends(get_current_user)
):
    """
    广播消息到所有连接的客户端
    管理员功能
    """
    try:
        if not current_user.get('is_superuser', False):
            raise HTTPException(status_code=403, detail="权限不足")

        await real_time_service.broadcast_system_notification(message, "info")
        return {
            "code": 200,
            "message": "消息广播成功",
            "data": None
        }
    except Exception as e:
        logger.error(f"广播消息失败: {e}")
        raise HTTPException(status_code=500, detail="广播消息失败")


@websocket_router.post("/refresh/{topic}")
async def force_refresh_topic(
    topic: str,
    current_user: dict = Depends(get_current_user)
):
    """
    强制刷新指定主题的数据
    管理员功能
    """
    try:
        if not current_user.get('is_superuser', False):
            raise HTTPException(status_code=403, detail="权限不足")

        await real_time_service.force_refresh_data(topic)
        return {
            "code": 200,
            "message": f"主题 {topic} 数据刷新已触发",
            "data": None
        }
    except Exception as e:
        logger.error(f"强制刷新失败: {e}")
        raise HTTPException(status_code=500, detail="强制刷新失败")


@websocket_router.get("/topics")
async def get_available_topics():
    """
    获取可用的订阅主题列表
    """
    try:
        from services.websocket_service import manager
        topics = list(manager.push_intervals.keys())
        topic_info = [
            {
                "topic": topic,
                "interval_seconds": interval,
                "description": f"{topic}数据每{interval}秒推送一次"
            }
            for topic, interval in manager.push_intervals.items()
        ]

        return {
            "code": 200,
            "message": "success",
            "data": {
                "topics": topic_info,
                "system_topic": "system"
            }
        }
    except Exception as e:
        logger.error(f"获取主题列表失败: {e}")
        raise HTTPException(status_code=500, detail="获取主题列表失败")